package com.gyj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gyj.common.CommonResult;
import com.gyj.user.dao.UserDao;
import com.gyj.user.model.User;
import com.gyj.user.service.HashRedisService;
import com.gyj.user.utils.ConstantKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Gao on 2018/9/30.
 */
@Service
public class HashRedisServiceImpl implements HashRedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserDao userDao;

    @Override
    public User getUserByIdHash(String id) {

        Object o = stringRedisTemplate.opsForHash().get(ConstantKey.USER_HASH_KEY, id);
        if (o != null && o != "null") {
            User user = JSONObject.parseObject((String) o, User.class);
            return user;
        }

        User user = userDao.findById(Integer.parseInt(id));
        if (user != null) {
            String userString = JSONObject.toJSONString(user);
            stringRedisTemplate.opsForHash().put(ConstantKey.USER_HASH_KEY, id, userString);
            //设置缓存失效时间，100s后失效
            //stringRedisTemplate.expire(ConstantKey.USER_KEY_HASH, 100L, TimeUnit.SECONDS);
        }

        return user;
    }

    @Override
    public CommonResult<List<User>> getUserListByIdsHash(List<Integer> ids) {

        List<User> userList = new ArrayList<>();
        CommonResult<List<User>> result = new CommonResult<List<User>>(userList);
        List idsString = ids.stream().map(Object::toString).collect(Collectors.toList());
        List userListString = stringRedisTemplate.opsForHash().multiGet(ConstantKey.USER_HASH_KEY + " ids" + idsString, idsString);
        if (userListString != null && userListString.size() > 0) {
            result.setSuccess(true);
            //TODO 还有问题，待调试
            result.setResult((List<User>) userListString);
            return result;
        }

        userList = userDao.findByIdIn(ids);
        if (!userList.isEmpty()) {
            for (User user : userList) {
                stringRedisTemplate.opsForHash().put(ConstantKey.USER_HASH_KEY + " ids" + idsString, user.getId(), JSONObject.toJSONString(user));
            }
        }

        result.setResult(userList);
        return result;
    }
}
